package com.clwl.supervise.superviseapp.util;

import com.clwl.supervise.superviseapp.entity.base.TsUser;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
public class UserHelper {

    private static Logger logger = LoggerFactory.getLogger(UserHelper.class);


    private static RedisTemplate<String,TsUser> userRedisTemplate;

    private static HttpServletRequest request;


    /** 加密算法 */
    public final static String hashAlgorithmName = "SHA-256";
    /** 循环次数 */
    public final static int hashIterations = 16;

    public static String sha256(String password, String salt) {
        return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString();
    }
    /**
     * 获取用户id
     * @return
     */
    public static Long getUserId(){
        String userToken = request.getHeader("token");//用户token
        if (!StringUtils.hasLength(userToken)) {
            return null;
        }

        logger.info("userToken:{}",userToken);
        TsUser user = UserHelper.userRedisTemplate.opsForValue().get(userToken);
        return user.getId();
    }

    /**
     * 获取用户信息
     * @return
     */
    public static TsUser getUserInfo(){
        String userToken = request.getHeader("token");//用户token
        if (!StringUtils.hasLength(userToken)) {
            return null;
        }
        logger.info("userToken:{}",userToken);
        TsUser user = UserHelper.userRedisTemplate.opsForValue().get(userToken);
        return user;
    }



    @Resource
    public void setRequest(HttpServletRequest request) {
        UserHelper.request = request;
    }

    @Autowired
    public  void setUserRedisTemplate(RedisTemplate<String, TsUser> userRedisTemplate) {
        UserHelper.userRedisTemplate = userRedisTemplate;
    }



}
